<?php
/*
* 
* Created by PhpStorm.
* Author: 初心 [jialin507@foxmail.com]
* Date: 2017/4/30
*/

/**
 * 采集内容
 * @param $url
 * @return array
 */
function get_content($url){
    $content = [];
    $result = [];
    $data = https_request($url);
    //采集标题
    $partern = '/id="stitle" title="([\s\S]*)">/U';
    preg_match($partern, $data, $result);
    $content['title'] =  count($result) > 1 ? $result[1] : "未采集到标题";
    //采集简介
    $partern = '/span data="([\s\S]*)" id="sintro">/U';
    preg_match($partern, $data, $result);
    $content['info'] =  count($result) > 1 ? $result[1] : "未采集到简介";
    //采集图片
    $partern = '/class="recipe_cover" src="(.*)"/U';
    preg_match($partern, $data, $result);
    $content['img_url'] =  count($result) > 1 ? $result[1] : "未采集到图片";
    //采集其他菜品的url
    $partern = '/<ul id="related_recipe">([\s\S]*)<\/ul>/U';
    preg_match($partern, $data, $result);
    $content['url_li'] = count($result) > 1 ? resolve_url_li($result[1]) : [];

    $content['url'] = $url;
    return $content;
}

/**
 * 处理采集数据中的其他url
 * @param $url_li
 * @return mixed|string
 */
function resolve_url_li($url_li){
    $result = [];
    $partern = '/a href="(.*)"/U';
    preg_match_all($partern, $url_li, $result);

    return count($result) > 1 ? $result[1] : '';
}

/**
 * 存储单个url
 * @param $new_urls
 * @param $old_urls
 * @param $url
 * @param int $is_new
 */
function urls_add(&$new_urls, &$old_urls, $url, $is_new = 1){
    if(in_array($url, $new_urls) || in_array($url, $old_urls)){
        //已存在URL列表中，直接返回
        return ;
    }
    $is_new ? $new_urls[] = $url : $old_urls[] = $url;
}

/**
 * 存储一组url
 * @param $new_urls
 * @param $old_urls
 * @param $url_all
 */
function urls_add_all(&$new_urls, &$old_urls, $url_all){
    for ($i=0; $i<count($url_all); $i++){
        urls_add($new_urls, $old_urls, $url_all[$i]);
    }
}

/**
 * 获取单个url
 * @param $urls
 * @return mixed
 */
function urls_get(&$urls){
    return array_shift($urls);
}

/**
 * url访问
 * @param $url
 * @return data
 */
function https_request($url, $post = '') {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    if (!empty($post)) {
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'ERROR' . curl_error($curl);
    }
    curl_close($curl);
    return $data;
}